package com.cea.papyrus.core.presentation.sorters;

import org.eclipse.uml2.uml.Element;
import org.eclipse.uml2.uml.NamedElement;

import com.cea.papyrus.diagraminterchange2.di2.Diagram;

/**
 * Comparator by feature ID.
 */
public class TypeSorter<T> implements java.util.Comparator<T> {

	/* (non-Javadoc)
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
	 */
	public int compare(T o1, T o2) {
		if(o1 instanceof Element && o2 instanceof Element) {
			return compare((Element)o1, (Element)o2);
		}
		if(o1 instanceof Diagram && o2 instanceof Diagram) {
			return compare(((Diagram)o1).getName(), ((Diagram)o2).getName());
		}
		return 0;
	}

	/**
	 * Compare Feature ID of the two eclasses of the element
	 * @param o1 the first element to be compared
	 * @param o2 the second element to be compared
	 * @return the difference between o1 and o2
	 */
	public int compare(Element o1, Element o2) {
		int value = o2.eClass().getClassifierID()-o1.eClass().getClassifierID();
		if(value == 0) {
			// just one test for instanceof, both of them have the same type
			if(o1 instanceof NamedElement) {
				String tmp;
				String name1 = (  (tmp = ((NamedElement)o1).getLabel()) != null ) ? tmp : "";
				String name2 = (  (tmp = ((NamedElement)o2).getLabel()) != null ) ? tmp : "";
				return name1.compareTo(name2);
			}
		}
		return value;
	}
	public int compare(String o1, String o2) {
		return o1.compareTo(o2);
	}
}
